package com.tian.arch.function.permission

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions
import androidx.fragment.app.Fragment

/**
 *  定义动作 去请求权限
 */
interface IRequestPermission {
    fun reqPermissions(vararg permissions: String)
    fun openAppSetting()
}

/**
 * 真正去做权限请求处理的Fragment
 */
class RealReqPermissionFragment : Fragment(), IRequestPermission {

    private var currentPermissions: Array<String>? = null

    private val reqPermissionsLauncher = registerForActivityResult(RequestMultiplePermissions()) {
        val allGranted = PermissionManager.onRequestPermissionResult(it)
        if (allGranted) {
            detachOneself()
            PermissionManager.cleanPermissionReq()
        }
    }

    private val openSettingLauncher = registerForActivityResult(
        object : ActivityResultContract<String, Int>() {
            override fun createIntent(context: Context, input: String): Intent {
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                intent.data = Uri.fromParts("package", input, null)
                return intent
            }

            override fun parseResult(resultCode: Int, intent: Intent?): Int {
                return resultCode
            }
        }
    ) {
        reqPermissionsLauncher.launch(currentPermissions)
    }

    override fun openAppSetting() {
        openSettingLauncher.launch(requireActivity().packageName)
    }

    override fun reqPermissions(vararg permissions: String) {
        this.currentPermissions = permissions as Array<String>
        reqPermissionsLauncher.launch(currentPermissions)
    }

    /**
     * 当权限申请成功后，detach掉fragment自身
     */
    private fun detachOneself() {
        // 在fragment调用的 请求权限
        if (parentFragment != null) {
            requireParentFragment().childFragmentManager.beginTransaction().detach(this).remove(this).commit()
        } else {
            requireActivity().supportFragmentManager.beginTransaction().detach(this).remove(this).commit()
        }
    }
}
